package mx.netbrain.dao.impl;

import java.util.List;

import mx.netbrain.dao.ThemeDao;
import mx.netbrain.model.Theme;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

public class ThemeDaoImpl implements ThemeDao {

	private static final Logger logger = Logger
			.getLogger(ThemeDaoImpl.class);
	
	@Override
	public Theme findById(Integer id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return (Theme) session.load(Theme.class, id);
	}

	@Override
	public void save(Theme theme) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(theme);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void update(Theme theme) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(theme);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Update: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public Theme findByInitial(String initial) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String sql = "from Theme as theme where theme.initial = :initial";
		Query query = session.createQuery(sql);
		query.setString("initial", initial);
		return (Theme) query.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Theme> listAll() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return session.createQuery("from Theme as theme").list();
	}

}